package com.xwq.xwqaiagent.app.LoveApp;

import com.xwq.xwqaiagent.advisor.MyLoggerAdvisor;
import com.xwq.xwqaiagent.advisor.ReReadingAdvisor;
import com.xwq.xwqaiagent.advisor.SensitiveWordAdvisor;
import com.xwq.xwqaiagent.chatmemory.DatabaseChatMemory;
import com.xwq.xwqaiagent.chatmemory.FileBasedChatMemory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.ChatOptions;
import org.springframework.ai.model.Media;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.stereotype.Component;
import org.springframework.util.MimeType;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Objects;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveAppWithMul {

    private final ChatClient chatClient;


    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    /**
     * 初始化AI客户端
     * @param
     */
    public LoveAppWithMul(OpenAiChatModel model, DatabaseChatMemory databaseChatMemory) {
        // 1.初始化基于文件的对话记忆
        String fileDir = System.getProperty("user.dir") + "/chat-memory";
        //ChatMemory chatMemory = new FileBasedChatMemory(fileDir);
        //2. 初始化基于内存的对话记忆
        //ChatMemory chatMemory = new InMemoryChatMemory();
        //3.初始化基于数据库的对话记忆
        //ChatMemory chatMemory = new DatabaseChatMemory();
        chatClient = ChatClient.builder(model)
                .defaultOptions(ChatOptions.builder().model("qwen-omni-turbo").build())
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(databaseChatMemory),
                        //自定义日志Advisor，可以按需开启
                        new MyLoggerAdvisor(),
                        //自定义 Re2推理增强 Advisor，可以按需开启
                        new ReReadingAdvisor(),
                        new SensitiveWordAdvisor()
                )
                .build();
    }

    /**
     * AI基础对话（支持记忆多轮对话）
     * @param message
     * @param chatId
     * @return
     */
    public Flux<String> doChat(String message, String chatId) {
        return chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .stream()
                .content();

    }

    /**
     * AI基础对话（支持记忆多轮对话）
     * @param
     * @param chatId
     * @return
     */
    public Flux<String> doChatWithMul(String message, String chatId, List<MultipartFile> files) {
        // 1.解析多媒体
        List<Media> medias = files.stream()
                .map(file -> new Media(
                                MimeType.valueOf(Objects.requireNonNull(file.getContentType())),
                                file.getResource()
                        )
                )
                .toList();

        return chatClient.prompt()
                .user(p -> p.text(message).media(medias.toArray(Media[]::new)))
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .stream()
                .content();
    }

    record LoveReport(String title, List<String> suggestions) {
    }


    /**
     * AI恋爱报告（演示结构化输出）
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport: {}", loveReport);
        return loveReport;
    }

}
